<template>
  <div class="design-index">
    <je-panel v-bind="lauoutOptions">
      <template #tbar>
        <je-toolbar style="height: 39px; background: #f7f9fc; border-bottom: 1px solid #e6e6e6">
          <je-button v-if="activeKey == 'design'" type="text" @click="saveTable">
            <template #icon><i class="fal fa-save"></i></template>{{ $t('btnSaveText') }}
          </je-button>
          <je-button
            v-if="activeKey == 'design' && tableInfo.RESOURCETABLE_TYPE != 'VIEW'"
            type="text"
            :loading="applyLoding"
            @click="applyClick"
          >
            <template #icon><i class="fal fa-check"></i></template
            >{{ $t('designView.btnApplyText') }}
          </je-button>
          <je-button
            v-if="
              activeKey == 'design' &&
              tableInfo.RESOURCETABLE_TYPE == 'VIEW' &&
              tableInfo.RESOURCETABLE_IMPORT != '1'
            "
            type="text"
            @click="openView('view')"
          >
            <template #icon><i class="fal fa-calendar-edit"></i></template
            >{{ $t('viewModal.TabDesignTitle') }}
          </je-button>
          <je-button type="text" @click="removeCache">
            <template #icon><i class="jeicon jeicon-broom"></i></template
            >{{ $t('designView.btnRemoveCacheText') }}
          </je-button>
          <!--  <je-button type="text" @click="upgradeTag">
            <template #icon><i class="fal fa-flag"></i></template
            >{{ $t('designView.btnUpgradeTagText') }}
          </je-button> -->
          <je-button
            v-if="
              activeKey == 'design' && ['TREE', 'VIEW'].indexOf(tableInfo.RESOURCETABLE_TYPE) == -1
            "
            type="text"
            @click="openView('keyStrategyAdjustment')"
          >
            <template #icon><i class="jeicon jeicon-from"></i></template
            >{{ $t('designView.btnStrategyAdjustment') }}
          </je-button>
          <je-button v-if="activeKey == 'design'" type="text" @click="openDicFunc">
            <template #icon><i class="fal fa-book"></i></template
            >{{ $t('designView.btnOpenDicFuncText') }}
          </je-button>
          <je-button v-if="activeKey == 'design'" type="text" @click="openFuncMenu">
            <template #icon><i class="fal fa-server"></i></template
            >{{ $t('designView.btnOpenFuncMenuText') }}
          </je-button>
          <je-button
            v-if="activeKey == 'DDL'"
            class="copyBtn"
            type="text"
            :data-clipboard-text="sqlData"
            @click="copySql"
          >
            <template #icon><i class="fal fa-copy"></i></template>{{ $t('designView.btnCopyText') }}
          </je-button>
          <TbFill />
          <span class="button-right">
            <span v-if="isCreate == '1'" class="right-state">{{
              $t('designView.createdText')
            }}</span>
            <span v-else class="right-state">{{ $t('designView.notCreateText') }}</span>
            <span class="right-context" @click="openDetails">
              {{ $t('designView.particularsText') }}
            </span>
          </span>
        </je-toolbar>
      </template>
      <template #default>
        <je-tabs
          v-model:activeKey="activeKey"
          :tab-position="tabPosition"
          class="index-tabs"
          @change="changeTabs"
        >
          <je-tab-pane key="design" :tab="$t('viewModal.TabDesignTitle')">
            <TableDesignView
              :tab-key="pkValue"
              :table-info-data="tableInfo"
              :old-data="oldData"
              :save-type="saveType"
              :apply-type="applyType"
              :refresh-column="refreshColumn"
              :product-data="productData"
              @callApplyClick="callApplyClick"
            />
          </je-tab-pane>
          <je-tab-pane key="relation" :tab="$t('designView.tabRelationTitle')"
            ><TableRelation
              :tab-key="pkValue"
              :table-info-data="tableInfo"
              :product-data="productData"
              :refresh-relation="refreshData.refreshRelation"
              @checkedTable="checkedTable"
          /></je-tab-pane>
          <je-tab-pane key="DDL" :tab="$t('viewModal.TabDdlTitle')">
            <TableDdl
              :tab-key="pkValue"
              :table-type="tableInfo.RESOURCETABLE_TYPE"
              @copySqlData="copySqlData"
            />
          </je-tab-pane>
          <je-tab-pane v-if="isCreate == '1'" key="SQL" :tab="$t('viewModal.TabSqlTitle')">
            <TableSql :tab-key="pkValue" :product-data="productData" :table-info-data="tableInfo"
          /></je-tab-pane>
        </je-tabs>
      </template>
    </je-panel>
    <je-modal
      v-model:visible="visible"
      :title="$t('designView.infoText')"
      :cancel-text="$t('btnCloseText')"
      class="design-modal"
      height="auto"
      :resize="false"
      button-align="center"
      width="500"
      :maximizable="false"
      @close="handleCancel"
    >
      <p>{{ $t('designView.tableNameText') }}：{{ tableInfo.RESOURCETABLE_TABLENAME }}</p>
      <p>{{ $t('designView.tableCodeText') }}：{{ tableInfo.RESOURCETABLE_TABLECODE }}</p>
      <p>{{ $t('designView.createUserNameText') }}：{{ tableInfo.SY_CREATEUSERNAME }}</p>
      <p>{{ $t('designView.createDeptNameText') }}：{{ tableInfo.SY_CREATEORGNAME }}</p>
      <p>{{ $t('designView.createTimeText') }}：{{ tableInfo.SY_CREATETIME }}</p>
      <p>{{ $t('designView.modifyUserNameText') }}：{{ tableInfo.SY_MODIFYUSERNAME }}</p>
      <p>{{ $t('designView.modifyDeptNameText') }}：{{ tableInfo.SY_MODIFYORGNAME }}</p>
      <p>{{ $t('designView.modifyTimeText') }}：{{ tableInfo.SY_MODIFYTIME }}</p>
      <template #buttons="modal">
        <je-button key="back" @click="modal.close()">{{ $t('btnCloseText') }}</je-button>
      </template>
    </je-modal>
    <ViewDesign
      v-if="modalType == 'view'"
      modal-show="update"
      :modal-data="tableInfo"
      :product-data="productData"
      @changeData="changeData"
    />
    <KeyStrategyAdjustment
      v-if="modalType == 'keyStrategyAdjustment'"
      :modal-data="tableInfo"
      :product-data="productData"
      @changeData="changeData"
    />
  </div>
</template>
<script>
  import { defineComponent, ref, onMounted, reactive, watch } from 'vue';
  import { Tabs, Button, Modal, Panel, Toolbar } from '@jecloud/ui';
  import TableDesignView from './table-index.vue';
  import TableRelation from '../table-relation/index.vue';
  import TableDdl from '../table-ddl/index.vue';
  import TableSql from '../table-sql/index.vue';
  import ViewDesign from '../view-design/index.vue';
  import KeyStrategyAdjustment from './modal/key-strategy-adjustment.vue';
  import VueEvent from '../../helper/model/event';
  import { copy } from '@jecloud/utils';
  import { useMicroStore } from '@common/store/micro-store';
  import { getAxiosBaseURL } from '@jecloud/utils';
  import { useGlobalStore } from '@common/store/global-store';

  import { getInfoById, clearTableCache, addUpTag, applyTable } from '../../api/index';

  export default defineComponent({
    name: 'TableDesignIndex',
    components: {
      JeTabs: Tabs,
      JeTabPane: Tabs.TabPane,
      TableDesignView,
      TableRelation,
      TableDdl,
      TableSql,
      JeModal: Modal,
      JeButton: Button,
      ViewDesign,
      JePanel: Panel,
      JeToolbar: Toolbar,
      TbFill: Toolbar.Fill,
      KeyStrategyAdjustment,
    },
    props: {
      tabKey: {
        type: String,
        default: '',
      },
      productData: {
        type: Object,
        required: true,
        default: () => {
          return {};
        },
      },
      syncRefresh: {
        type: Boolean,
        default: true,
      },
    },
    emits: ['changeTabData'],
    setup(props, { emit }) {
      const microStore = useMicroStore();
      const tabPosition = ref('bottom');
      const activeKey = ref('design');
      //主键ID
      const pkValue = ref(props.tabKey);
      //table数据
      let tableInfo = reactive({});
      const oldData = {};
      //表是否创建
      let isCreate = ref('');
      const typeData = { TREE: '树形表', PT: '普通表', VIEW: '视图' };
      //点击保存按钮给子组件传参，调用子组件的保存方法
      const saveType = ref(true);
      const applyType = ref(true);

      const refreshColumn = ref(true);

      const modalType = ref('');

      //刷新组件参数
      const refreshData = reactive({
        refreshRelation: true,
      });

      //同步结构刷新数据
      watch(
        () => props.syncRefresh,
        () => {
          refreshColumn.value = !refreshColumn.value;
          refreshData.refreshRelation = !refreshData.refreshRelation;
        },
      );

      //获得表的数据
      const getColumnData = () => {
        getInfoById({
          tableCode: 'JE_CORE_RESOURCETABLE',
          pkValue: pkValue.value,
        })
          .then((obj) => {
            const data = obj.data;
            data.tableTypeName = typeData[data.RESOURCETABLE_TYPE];
            for (let key in data) {
              tableInfo[key] = data[key];
              oldData[key] = data[key];
            }
            isCreate.value = data.RESOURCETABLE_ISCREATE;
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };
      onMounted(() => {
        getColumnData();
      });

      //保存操作
      const saveTable = () => {
        //点击保存按钮给子组件传参，调用子组件的保存方法
        saveType.value = !saveType.value;
      };

      //应用操作
      const applyClick = () => {
        applyLoding.value = true;
        //先调用表格列保存方法
        applyType.value = !applyType.value;
        //表格列保存后才应用表
      };

      const callApplyClick = (type) => {
        if (type == 'notApply') {
          applyLoding.value = false;
        } else {
          applyTableClick();
        }
      };

      const applyLoding = ref(false);

      //应用方法
      const applyTableClick = () => {
        applyTable(
          {
            JE_CORE_RESOURCETABLE_ID: pkValue.value,
            SY_PRODUCT_ID: props.productData.productId,
          },
          {
            pd: props.productData.productCode,
          },
        )
          .then((data) => {
            Modal.notice(data.message, 'success');
            getColumnData();
            refreshColumn.value = !refreshColumn.value;
            VueEvent.emit('loadData', {
              type: 'loadTree',
            });
            refreshData.refreshRelation = !refreshData.refreshRelation;
            applyLoding.value = false;
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
            applyLoding.value = false;
          });
      };

      //设计视图操作
      const openView = (type) => {
        modalType.value = type;
      };

      //设计视图数据改变触发
      const changeData = (val, datas) => {
        modalType.value = '';
        if (val == 'add') {
          //刷新左侧树和tab标签
          VueEvent.emit('loadData', {
            title: datas.title,
            key: datas.key,
            type: 'update',
          });
          //刷新表单的数据
          getColumnData();
          //刷新表格列的数据
          refreshColumn.value = !refreshColumn.value;
        }
        if (val == 'refreshForm') {
          Object.assign(tableInfo, datas);
        }
      };

      //清空缓存操作
      const removeCache = () => {
        clearTableCache(
          {
            RESOURCETABLE_TABLECODE: tableInfo.RESOURCETABLE_TABLECODE,
          },
          {
            pd: props.productData.productCode,
          },
        )
          .then((data) => {
            Modal.notice(data.message, 'success');
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      //升级标记操作
      const upgradeTag = () => {
        addUpTag({
          type: 'TABLE',
          ids: pkValue.value,
        })
          .then((data) => {
            Modal.notice(data.message, 'success');
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      //复制Sql
      const sqlData = ref('');
      const copySqlData = (data) => {
        sqlData.value = data;
      };
      const copySql = () => {
        copy(sqlData.value);
        Modal.notice('复制成功！', 'success');
      };
      // 打开数据字典功能
      const openDicFunc = () => {
        microStore.emitAdmin('admin-openmenu', {
          menuId: 'fe8666a4-7d6f-4bb6-8d70-49d766c82c33',
          layout: 'app',
        });
      };
      // 打开应用中心功能
      const openFuncMenu = () => {
        // microStore.emitAdmin('admin-openmenu', {
        //   menuId: 'aa413989-2743-4fe5-87e1-8c822275038c',
        //   layout: 'app',
        // });
        const { activePlan } = useGlobalStore();
        window.open(
          `${getAxiosBaseURL()}/#/${activePlan}/app/JE_CORE_FUNCTION?productId=${
            props.productData.productId
          }`,
        );
      };
      //详情操作
      const visible = ref(false);
      const handleCancel = () => {
        visible.value = false;
      };
      const openDetails = () => {
        visible.value = true;
      };

      const changeTabs = function (check) {
        activeKey.value = check;
      };

      const checkedTable = function (tabData) {
        emit('changeTabData', tabData);
      };

      return {
        pkValue,
        tableInfo,
        oldData,
        isCreate,
        tabPosition,
        activeKey,
        changeTabs,
        saveTable,
        applyClick,
        openView,
        removeCache,
        upgradeTag,
        handleCancel,
        openDetails,
        copySql,
        openDicFunc,
        openFuncMenu,
        visible,
        saveType,
        sqlData,
        refreshColumn,
        copySqlData,
        modalType,
        changeData,
        centered: true,
        checkedTable,
        applyType,
        callApplyClick,
        applyLoding,
        refreshData,
        lauoutOptions: { tbar: { size: 40 } },
      };
    },
  });
</script>
<style lang="less" scoped>
  .design-index {
    height: 100%;
    .index-tabs {
      height: 100%;
      .ant-tabs-nav-wrap {
        height: 40px !important;
      }
    }
  }
</style>
<style lang="less">
  .design-modal {
    .ant-modal-footer {
      text-align: center;
    }
    .je-modal--content {
      background: #f9f9f9;
      padding: 10px;
      p {
        font-size: 16px;
        line-height: 24px;
        color: #3f3f3f;
        font-weight: Normal;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
  .design-index {
    .button-right {
      font-size: 14px;
      font-weight: Bold;
      margin-right: 30px !important;
      .right-state {
        color: #008103;
      }
      .right-context {
        margin-left: 14px;
        color: #3265f5;
        cursor: pointer;
      }
    }

    .ant-tabs.index-tabs {
      .ant-tabs-nav {
        border-bottom: 0;
        border-right: 0;
        background: #f7f9fc;
        margin-top: 0;
        border-top: 0 !important;
      }
      .ant-tabs-nav-wrap {
        height: 40px !important;
        border-bottom: 0 !important;
        border-top: 1px solid #e6e6e6;
        .ant-tabs-nav-list {
          .ant-tabs-tab {
            padding: 12px 22px;
          }
          .ant-tabs-tab + .ant-tabs-tab {
            margin: 0 0 0 0;
          }
          .ant-tabs-tab.ant-tabs-tab-active {
            background: @primary-color;
            .ant-tabs-tab-btn {
              color: #ffffff;
            }
          }
          .ant-tabs-ink-bar.ant-tabs-ink-bar-animated {
            height: 0px;
          }
        }
      }
      .ant-tabs-nav {
        //padding: 0 0 0 16px;
      }
    }
  }
</style>
